package cirno.open.api.controller;

import cirno.open.api.common.BaseResponse;
import cirno.open.api.common.ResultUtils;
import cirno.open.api.entity.ExecuteRequest;
import cirno.open.api.entity.ExecuteResponse;
import cirno.open.api.enums.LanguageCmdEnum;
import cirno.open.api.service.DockerSandboxService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/code")
public class CodeExecutorController {

    private final DockerSandboxService dockerSandboxService;

    public CodeExecutorController(DockerSandboxService dockerSandboxService) {
        this.dockerSandboxService = dockerSandboxService;
    }

    /**
     * 获取支持的language列表
     * @return language列表
     */
    @GetMapping("/supports")
    public BaseResponse<List<String>> getSupports(HttpServletRequest req,HttpServletResponse resp) {
        return ResultUtils.success(LanguageCmdEnum.getLanguages());
    }

    /**
     * 编译代码(检测语法通过)
     * @param request
     * @return 执行代码结果 + 错误信息
     */
    @PostMapping("compile")
    public BaseResponse<ExecuteResponse> compileCode (@RequestBody ExecuteRequest request, HttpServletRequest req,HttpServletResponse resp) {
        dockerSandboxService.validateParams(request);
        LanguageCmdEnum language = LanguageCmdEnum.getEnumByValue(request.getLanguage());
        String code = request.getCode();
        return ResultUtils.success(dockerSandboxService.compile(language,code));
    }

    /**
     * 编译(检测语法通过) -> 执行代码
     * @param request
     * @return 执行代码结果 + 错误信息
     */
    @PostMapping("execute")
    public BaseResponse<ExecuteResponse> executeCode (@RequestBody ExecuteRequest request , HttpServletRequest req,HttpServletResponse resp) {
        dockerSandboxService.validateParams(request);
        LanguageCmdEnum language = LanguageCmdEnum.getEnumByValue(request.getLanguage());
        String code = request.getCode();
        return ResultUtils.success(dockerSandboxService.execute(language,code,false));
    }
}
